package main

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
	"xinyu/MyLog"
	"xinyu/controller"
	"xinyu/global"
	"xinyu/middleware"
	"xinyu/model"
	"xinyu/router"
	"xinyu/setting"
)

func init() {
	err := setupSetting()
	if err != nil {
		MyLog.Log.Error("初始化配置文件失败：", err)
	}
}

// @title 心语
// @version 1.0
// @description Go 小辣条编程之旅
func main() {
	model.DB.Init(global.DatabaseSetting)
	controller.InitController()

	gin.SetMode(global.ServerSetting.RunMode)
	r := gin.New()
	router.Load(
		r,
		middleware.Logging(),
		middleware.Cors(),
	)

	MyLog.Log.Info("启动HTTP服务，监听端口：", global.ServerSetting.HttpPort)
	s := &http.Server{
		Addr:         ":" + global.ServerSetting.HttpPort,
		Handler:      r,
		ReadTimeout:  global.ServerSetting.ReadTimeout,
		WriteTimeout: global.ServerSetting.WriteTimeout,
	}
	MyLog.Log.Error("启动服务错误：", s.ListenAndServe())
}

func setupSetting() error {
	setting, err := setting.NewSetting()
	if err != nil {
		return err
	}

	err = setting.ReadSection("Server", &global.ServerSetting)
	if err != nil {
		return err
	}

	err = setting.ReadSection("App", &global.AppSetting)
	if err != nil {
		return err
	}

	err = setting.ReadSection("Database", &global.DatabaseSetting)
	if err != nil {
		return err
	}

	err = setting.ReadSection("JWT", &global.JWTSetting)
	if err != nil {
		return err
	}

	err = setting.ReadSection("QiNiu", &global.QiNiuSetting)
	if err != nil {
		return err
	}

	global.ServerSetting.ReadTimeout *= time.Second
	global.ServerSetting.WriteTimeout *= time.Second
	global.JWTSetting.Expire *= time.Hour
	return nil
}
